import Cookies from 'js-cookie';

const TokenKey = 'Admin-Token';
const UserKey = 'Admin-User';
const TimeKey = 'Admin-Time';
const BtnsKey = 'Admin-Btn';
const RoleKey = 'Admin-Role';
const RouteKey = 'Current-Routes';

/**
 * 检查是否存在cookie信息
 * @param {String} name keyword
 */
export function checkLoginToken() {
    if (Cookies.get(TokenKey)) {
        // 验证时间
        if (moment().isAfter(Cookies.get(TimeKey))) {
            // 过期后删除
            removeLoginToken();
            return false;
        } else {
            return true;
        }
    }
    return false;
}

/**
 * 存储登录用户信息
 * @param {String} token 
 * @param {String} user 
 * @param {Number} expire 
 */
export function setLoginToken(token, user, expire) {
    // console.log(Cookies.get('Admin-User', { domain: 'middleground-portal.haier-ioc.com' }));
    return Cookies.set(TokenKey, token) && Cookies.set(UserKey, user) && Cookies.set(TimeKey, expire);
}

/**
 * 获取登录用户信息
 */
export function getLoginToken() {
    if (!checkToken()) return null;
    return {
        authorization: Cookies.get(TokenKey),
        user: Cookies.get(UserKey)
    };
}

/**
 * 移除登录用户信息
 */
export function removeLoginToken() {
    Cookies.remove(TokenKey);
    Cookies.remove(UserKey);
    Cookies.remove(TimeKey);
    Cookies.remove(BtnsKey);
}

// 获取token信息
export function getToken() {
    return Cookies.get(TokenKey);
}

// 获取登录用户信息
export function getUser() {
    return Cookies.get(UserKey);
}

export function getUserAdmin() {
    const user = getUser();
    if (user) {
        return JSON.parse(user).id == 1 || JSON.parse(user).isAdmin == 1;
    }
    return false;
}

// 存储路由信息
export function setRoutes(routes) {
    return localStorage.setItem(RouteKey, JSON.stringify(routes));
}

// 获取路由信息
export function getRoutes() {
    return localStorage.getItem(RouteKey) ? JSON.parse(localStorage.getItem(RouteKey)) : [];
}

// 清除路由信息
export function removeRoutes() {
    return localStorage.removeItem(RouteKey);
}

// 设置用户的所有权限按钮
export function setBtns(btns) {
    return Cookies.set(BtnsKey, JSON.stringify(btns));
}

export function getBtns() {
    return Cookies.get(BtnsKey) ? JSON.parse(Cookies.get(BtnsKey)) : [];
}

// 设置用户登录时选择的登录角色
export function setUserRole(role) {
    return Cookies.set(RoleKey, role);
}

export function getUserRole() {
    return Cookies.get(RoleKey) ? Cookies.get(RoleKey) : null;
}
